package common

import (
	"encoding/json"
	"fmt"
	"github.com/astaxie/beego/httplib"
	"log"
)

var (
	url = "http://39.106.40.170:9200/"
)

func EsAdd(index string, body interface{}, id string) error {
	fmt.Println(id)
	req := httplib.Post(url + index + "/_doc/" + id)
	req.JSONBody(body)
	res, err := req.String()
	if err != nil {
		return err
	}
	fmt.Println("111111111111")
	fmt.Println(res)
	return nil
}

func EsUpdate(index string, body interface{}, id string) error {
	fmt.Println(id)
	req := httplib.Post(url + index + "/_update/" + id)
	req.JSONBody(body)
	res, err := req.String()
	if err != nil {
		return err
	}
	fmt.Println("111111111111")
	fmt.Println(res)
	return nil
}

type S struct {
	Query struct {
		Match struct {
			Name string `json:"Name"`
		} `json:"match"`
	} `json:"query"`
	Highlight struct {
		Fields struct {
			Name struct {
				PreTags  string `json:"pre_tags"`
				PostTags string `json:"post_tags"`
			} `json:"Name"`
		} `json:"fields"`
	} `json:"highlight"`
	From int `json:"from"`
	Size int `json:"size"`
	Sort struct {
		Id struct {
			Order string `json:"order"`
		} `json:"Id"`
	} `json:"sort"`
}

func EsSearch(index string, search string, page int) (ResData, error) {
	//偏移量
	offect := (page - 1) * 20
	log.Println(search)
	req := httplib.Post(url + index + "/_search")
	s := S{}
	s.Query.Match.Name = search
	s.Highlight.Fields.Name.PreTags = "<a color='red'>"
	s.Highlight.Fields.Name.PostTags = "</a>"
	s.From = offect
	//显示页数
	s.Size = 20
	s.Sort.Id.Order = "asc"
	req.JSONBody(s)
	var r ResData
	res, _ := req.String()
	json.Unmarshal([]byte(res), &r)
	return r, nil
}

// 统计总数
type Count struct {
	Size int `json:"size"`
	Aggs struct {
		Categories struct {
			ValueCount struct {
				Field string `json:"field"`
			} `json:"value_count"`
		} `json:"categories"`
	} `json:"aggs"`
}

type CountRes struct {
	Took     int  `json:"took"`
	TimedOut bool `json:"timed_out"`
	Shards   struct {
		Total      int `json:"total"`
		Successful int `json:"successful"`
		Skipped    int `json:"skipped"`
		Failed     int `json:"failed"`
	} `json:"_shards"`
	Hits struct {
		Total struct {
			Value    int    `json:"value"`
			Relation string `json:"relation"`
		} `json:"total"`
		MaxScore interface{}   `json:"max_score"`
		Hits     []interface{} `json:"hits"`
	} `json:"hits"`
	Aggregations struct {
		Categories struct {
			Value int `json:"value"`
		} `json:"categories"`
	} `json:"aggregations"`
}

// 根据id统计
func CountData(index string) CountRes {
	var c Count
	req := httplib.Post(url + index + "/_search")
	c.Aggs.Categories.ValueCount.Field = "Id"
	req.Body(c)
	res, err := req.String()

	var resData CountRes
	json.Unmarshal([]byte(res), &resData)
	if err != nil {
		fmt.Println("统计失败：", err.Error())
	}
	return resData
}

type O struct {
	Query struct {
		MatchAll struct {
		} `json:"match_all"`
	} `json:"query"`
	Sort struct {
		Looknum struct {
			Order string `json:"order"`
		} `json:"Looknum"`
	} `json:"sort"`
}

// 根据浏览量排行数据
func Sort(index string) (SortRes, error) {
	//偏移量
	req := httplib.Post(url + index + "/_search")
	o := O{}
	o.Sort.Looknum.Order = "desc"
	req.JSONBody(o)
	var s SortRes
	res, _ := req.String()
	fmt.Println(res)
	err := json.Unmarshal([]byte(res), &s)
	if err != nil {
		return SortRes{}, err
	}
	return s, nil
}

type Os struct {
	Query struct {
		Match struct {
			Name string `json:"Name"`
		} `json:"match"`
	} `json:"query"`
	Sort struct {
		Looknum struct {
			Order string `json:"order"`
		} `json:"Looknum"`
	} `json:"sort"`
}

// 根据搜索内容排序
func SortSearch(index string, search string) (SortRes, error) {
	//偏移量
	req := httplib.Post(url + index + "/_search")
	o := Os{}
	o.Query.Match.Name = search
	o.Sort.Looknum.Order = "desc"
	req.JSONBody(o)
	var s SortRes
	res, _ := req.String()
	fmt.Println(res)
	err := json.Unmarshal([]byte(res), &s)
	if err != nil {
		return SortRes{}, err
	}
	return s, nil
}

type SortRes struct {
	Took     int  `json:"took"`
	TimedOut bool `json:"timed_out"`
	Shards   struct {
		Total      int `json:"total"`
		Successful int `json:"successful"`
		Skipped    int `json:"skipped"`
		Failed     int `json:"failed"`
	} `json:"_shards"`
	Hits struct {
		Total struct {
			Value    int    `json:"value"`
			Relation string `json:"relation"`
		} `json:"total"`
		MaxScore interface{} `json:"max_score"`
		Hits     []struct {
			Index  string      `json:"_index"`
			Type   string      `json:"_type"`
			Id     string      `json:"_id"`
			Score  interface{} `json:"_score"`
			Source struct {
				Id      int    `json:"Id"`
				UserId  int    `json:"UserId"`
				Name    string `json:"Name"`
				Path    string `json:"Path"`
				Address string `json:"Address"`
				Version int    `json:"Version"`
				Public  int    `json:"Public"`
				Looknum int    `json:"Looknum"`
			} `json:"_source"`
			Sort []int `json:"sort"`
		} `json:"hits"`
	} `json:"hits"`
}

type ResData struct {
	Took     int  `json:"took"`
	TimedOut bool `json:"timed_out"`
	Shards   struct {
		Total      int `json:"total"`
		Successful int `json:"successful"`
		Skipped    int `json:"skipped"`
		Failed     int `json:"failed"`
	} `json:"_shards"`
	Hits struct {
		Total struct {
			Value    int    `json:"value"`
			Relation string `json:"relation"`
		} `json:"total"`
		MaxScore interface{} `json:"max_score"`
		Hits     []struct {
			Index  string      `json:"_index"`
			Type   string      `json:"_type"`
			Id     string      `json:"_id"`
			Score  interface{} `json:"_score"`
			Source struct {
				Id      int    `json:"Id"`
				UserId  int    `json:"UserId"`
				Name    string `json:"Name"`
				Path    string `json:"Path"`
				Address string `json:"Address"`
				Version int    `json:"Version"`
				Public  int    `json:"Public"`
				Looknum int    `json:"Looknum"`
			} `json:"_source"`
			Highlight struct {
				Name []string `json:"Name"`
			} `json:"highlight"`
			Sort []int `json:"sort"`
		} `json:"hits"`
	} `json:"hits"`
}
type I struct {
	Settings struct {
		Index struct {
			Analysis struct {
				Analyzer struct {
					Default struct {
						Type string `json:"type"`
					} `json:"default"`
				} `json:"analyzer"`
			} `json:"analysis"`
		} `json:"index"`
	} `json:"settings"`
	Mappings struct {
		Properties struct {
			Description struct {
				Type     string `json:"type"`
				Analyzer string `json:"analyzer"`
			} `json:"description"`
		} `json:"properties"`
	} `json:"mappings"`
}

// 创建ik分词索引
func EsPut(index string, analyzer string, types string) error {
	req := httplib.Post(url + index)
	p := I{}
	p.Settings.Index.Analysis.Analyzer.Default.Type = analyzer
	p.Mappings.Properties.Description.Type = types
	p.Mappings.Properties.Description.Analyzer = analyzer
	req.JSONBody(p)
	res, err := req.String()
	if err != nil {
		return err
	}
	fmt.Println(res)
	return nil
}
